package org.sonar.plugin.deltacoverage;

import java.io.File;
import java.io.FileNotFoundException;

import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.Decorator;
import org.sonar.api.batch.DecoratorContext;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Resource;


public class DeltaCoverageDecorator implements Decorator {

	private static final String REPORT_NAME = "DeltaCoverageReport.xml";
	private static final Logger LOG = LoggerFactory.getLogger(DeltaCoverageDecorator.class);

	public void decorate(Resource resource, DecoratorContext context) {

		if (shouldDecorate(resource, context)) {

			File coverageReport = null;
			Project project = (Project) resource;
			String reportPath = (String) project.getProperty(DeltaCoveragePlugin.REPORT_PATH_KEY);
			if (reportPath != null) {
				LOG.info("DeltaCoverage reportPath = " + reportPath);
				coverageReport = new File(reportPath);
			} else {
				Log.info("DeltaCoverage reportPath = "+project.getFileSystem().getBuildDir()+"/"+REPORT_NAME);
				coverageReport = new File(project.getFileSystem().getBuildDir(), REPORT_NAME);
			}

			try {
				ModuleCoverage coverage = CoverageReportReader.getCoverageData(coverageReport);
				Double newCoverage = (double)(coverage.getHitLines()+coverage.getHitBranches())/(coverage.getTotalLines()+coverage.getTotalBranches()) * 100;
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_LINE_COVERAGE, coverage.getLineRate() * 100));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_LINES, (double)coverage.getTotalLines()));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_UNCOVERED_LINES, (double)(coverage.getTotalLines() - coverage.getHitLines())));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_BRANCH_COVERAGE, coverage.getBranchRate() * 100));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_UNCOVERED_CONDITIONS, (double)(coverage.getTotalBranches() - coverage.getHitBranches())));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_CONDITIONS, (double)coverage.getTotalBranches()));
				context.saveMeasure(new Measure(DeltaCoverageMetrics.DELTA_COVERAGE, newCoverage ));
				
			} catch (FileNotFoundException e) {
				LOG.warn("Could not find delta coverage report in build directory " + project.getFileSystem().getBuildDir() + ". Set property " + DeltaCoveragePlugin.REPORT_PATH_KEY);
			}

		}
	}


	private boolean shouldDecorate(Resource resource, DecoratorContext context) {
		return resource.getQualifier().equals(Qualifiers.PROJECT);
	}

	public boolean shouldExecuteOnProject(Project arg0) {
		return true;
	}

}
